package cn.acewill.yxd.yunxundian.pubClass;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.simpleAdapter;
import cn.acewill.yxd.yunxundian.componet.NetWorkStateReceiver;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Employee;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.ui.MainActivity;

/**
 * Created by XXX on 2017/5/17.
 */

public class SubmitReport extends BaseActivity implements View.OnClickListener{
    private int schId;
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private TextView titleText,storeName,scheTitle;
    private Button submitData;
    private Button cancelDate;
    private LinearLayout sureSubmit;
    private Schedule thisSch;
    private TextView status,cman;
    //设置跳转的耗时
    private int time=2000;
    private Dialog dialog=null;
    private RadioGroup myRadioGroup;
    private String success="数据上传成功";
    private String failed="数据上传失败";
    private int Tomanid=0;
    //shangchuan
    private int needtodo=0;
    //推送人数据显示
    private  ListView myScoreList;
    //推送人dialog
    private Dialog myDialog;
    //推送人的数据
    private ArrayList<Employee> emp;
    private  LinearLayout hindTuisong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleBar("数据上传");
        setContentView(R.layout.datasubmit);
        super.onCreate(savedInstanceState);
        //拿到门店的id
        schId=getIntent().getIntExtra("schId",-1);
        if(!checkCanPost())
        {
            if(dialog!=null)
                dialog.dismiss();
            this.finish();
            return;
        }
        //Button sureBtn= (Button) findViewById(R.id.sureBtn);
        //sureBtn.setVisibility(View.GONE);
        Dialog dialog = new Dialog(this, R.style.BottomDialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定
        dialog.setContentView(R.layout.submitview);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode== KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0)
                    return true;
                else
                   return false;
            }
        });
        final Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.AnimBottom);
        final WindowManager.LayoutParams lp = window.getAttributes();
        lp.gravity = Gravity.BOTTOM; // 紧贴底部
        lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平
        lp.height = this.getWindowManager().getDefaultDisplay().getHeight() * 3/ 5;
        window.setAttributes(lp);
        dialog.show();
        /*初始化控件*/
        initView(dialog);
    }

    public boolean checkCanPost()
    {
        boolean flag=true;
        if(schId==-1)
            return false;

        return flag;
    }

    public void postall() {
        List<tempLostRR> temp = null;
        try {
            //拿到上传的数据
            temp = db.selector(tempLostRR.class).where("schId", "=", schId).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        final String currentTime = sdf.format(date);
        final String currentTimeT = currentTime.replace(' ', 'T');
        try {
            thisSch = db.selector(Schedule.class).where("ID", "=", schId).findFirst();
            if (thisSch != null) {
                //upLoadDsOrScore(schId,currentTime,temp);
                status.setText("正在打包失分项");
                if (!TextUtils.isEmpty(cman.getText().toString().trim())) {
                    needtodo = 1;
                } else {
                    needtodo = 0;
                }
                Map<String, Object> map = new HashMap<>();
                Gson gson = new Gson();
                //失分项
                map.put("task", "postall");
                map.put("schid", schId);
                if (thisSch.getRealStartTime() != null)
                    map.put("schstarttime", thisSch.getRealStartTime().replace("T", " "));
                else
                    map.put("schstarttime", currentTime);
                map.put("tIrrList", gson.toJson(temp));
                map.put("needtodo", needtodo);
                map.put("toshopman", Tomanid);
                //图片
                int count = 0;
                status.setText("正在打包图片和视频");
                if (temp != null && temp.size() > 0) {
                for (tempLostRR rr : temp) {
                    String photo = rr.getJpgStr();
                    String video = rr.getVideoStr();
                    //去掉最后一个逗号,
                    if (!TextUtils.isEmpty(photo)) {
                        String[] ss = photo.substring(0, photo.length() - 1).split(",");
                        //判断文件是否存在
                        for (int i = 0; i < ss.length; i++) {
                            File file = new File(ss[i]);
                            if (file.exists()) {
                                map.put("uploadfile" + count, file);
                                count++;
                            }
                        }
                    }
                    if (!TextUtils.isEmpty(video)) {
                        String[] sp = video.substring(0, video.length() - 1).split(",");

                        for (int k = 0; k < sp.length; k++) {
                            File file = new File(sp[k]);
                            if (file.exists()) {
                                map.put("uploadfile" + count, file);
                                count++;
                            }
                        }
                    }

//                    for (String s : ss) {
//
//
//                        if (s.equals(""))
//                            continue;
//                        //裁剪时已经进行压缩
//                        File f = new File(s);
//                        map.put("uploadfile" + count, f);
//                        count++;
//                    }
//                    for (String p : sp) {
//                        if (p.equals(""))
//                            continue;
//                        File f = new File(p);
//                        map.put("uploadfile" + count, f);
//                        count++;
//                    }
                }
            }
                //签名
                CommonMapBean cmb = new CommonMapBean();
                cmb = db.selector(CommonMapBean.class).where("CmType", "=", "门店签名")
                        .and("IndexNum", "=", schId + "")
                        .findFirst();
                if (cmb != null) {
                    status.setText("打包上传门店签名...");
                    if (!cmb.getCmValue().toString().equals("")) {
                        File f = new File(cmb.getCmValue().toString());
                        map.put("signjpg", f);
                    }
                }
                pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        String[] resArry = result.split("\\|");
                        if (resArry[0].equals("200")) {
                            Toast.makeText(SubmitReport.this, "数据上传成功", Toast.LENGTH_SHORT).show();
                            Schedule schedule = null;
                            CommonMapBean cmb = new CommonMapBean();
                            cmb.setCmType("fenshu");
                            cmb.setServerId(schId);
                            cmb.setCmValue(resArry[3]);
                            try {
                                db.saveOrUpdate(cmb);
                                schedule = db.selector(Schedule.class).where("ID", "=", schId + "").findFirst();
                                schedule.setStates(3);
                                schedule.setRealEndTime(currentTimeT);
                                db.saveOrUpdate(schedule);
                            } catch (DbException e) {
                                e.printStackTrace();

                            }
                            status.setText("上传完毕,正在更新状态");
                            completeUpload(success);
                        } else if (resArry[0].equals("201")) {
                            titleText.setText("网络开小差了");
                            status.setText("上传失败，请稍后再试");
                        } else {
                            titleText.setText("网络开小差了");
                            status.setText("上传失败" + " " + result);
                        }
                    }
                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        //Toast.makeText(SubmitReport.this,"数据上传失败",Toast.LENGTH_SHORT).show();
                        titleText.setText("网络开小差了");
                        status.setText("上传失败" + " " + ex.toString());
                    }
                });
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void initView(final Dialog dialog){
        this.cman= (TextView) dialog.findViewById(R.id.cman);
        this.scheTitle= (TextView) dialog.findViewById(R.id.scheTitle);
        this.titleText= (TextView)  dialog.findViewById(R.id.titleText);
        this.storeName= (TextView)  dialog.findViewById(R.id.storeName);
        this.submitData= (Button)  dialog.findViewById(R.id.submitData);
        this.cancelDate=(Button)dialog.findViewById(R.id.cancelSubmit);
        this.sureSubmit= (LinearLayout) dialog.findViewById(R.id.sureSubmit);
        this.status= (TextView) dialog.findViewById(R.id.status);
        hindTuisong= (LinearLayout) dialog.findViewById(R.id.Linear);
        //拿到推送人数据
        getTuiSongRenData();
        sureSubmit.setVisibility(View.GONE);
        submitData.setOnClickListener(this);
        cancelDate.setOnClickListener(this);
        this.myRadioGroup= (RadioGroup) dialog.findViewById(R.id.myRadioGroup);
        this.myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId){
                    case R.id.btn_sure:
                        //拿到推送人的数据
                         myDialog=new Dialog(dialog.getContext());
                        View view = LayoutInflater.from(dialog.getContext()).inflate(R.layout.scoretype1_dialog, null);
                        TextView listTitle = (TextView) view.findViewById(R.id.listTitle);
                        listTitle.setText("推送人");
                         myScoreList = (ListView) view.findViewById(R.id.myList);
                        myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        myDialog.setContentView(view);
                        //判断推送人数据是否为空
                        if (emp!=null){
                            simpleAdapter adapter=new simpleAdapter(SubmitReport.this,emp);
                            myScoreList.setAdapter(adapter);
                            myScoreList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    Employee employee= (Employee) parent.getItemAtPosition(position);
                                    Tomanid=employee.getID();
                                    cman.setText(employee.getFirstName());
                                    myDialog.dismiss();
                                }
                            });
                        }

                        myDialog.show();

                        break;
                    case R.id.btn_cancel:
                        //清空数据
                        if (!TextUtils.isEmpty(cman.getText().toString().trim())){
                            cman.setText("");
                        }
                        Tomanid=0;
                        break;
                }
            }
        });


        try {
            Schedule schedule=db.selector(Schedule.class).where("ID","=",schId).findFirst();
//            if(schedule.getIsNeedShopReport()>=1&&schedule.getStates()>=3){
//                Linear.setVisibility(View.VISIBLE);
//            }else{
//                Linear.setVisibility(View.GONE);
//            }

            Shop shop =db.selector(Shop.class).where("ID","=",schedule.getShopID()).findFirst();
            storeName.setText("当前门店名称："+shop.getShopName());
            scheTitle.setText("当前任务名称："+schedule.getTitle());
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.submitData:
                /*
                * 1.数据的提交，首先判断网络状况
                * 2.判断数据的内容
                * 3.判断数据提交的状态
                * */
                if (NetWorkStateReceiver.whetherConnectNetWork==1){
                    //upLoadCheck(schId);
                    postall();
                    sureSubmit.setVisibility(View.VISIBLE);
                    titleText.setText("上传进行中....");
                }else{
                    //没网络
                    Toast.makeText(SubmitReport.this,"当前无网络连接，请检查网络状态",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.cancelSubmit:
                if(dialog!=null)
                    dialog.dismiss();
                SubmitReport.this.finish();
        }
    }

    public void getTuiSongRenData(){
        final ProgressDialog pdialog=new ProgressDialog(this);
        pdialog.setMessage("加载中");
        pdialog.show();
        Map<String,String> map=new HashMap<>();
        map.put("task","getShopTodoEmpList");
        map.put("schid",schId+"");
        try {
            OkHttpManger.getInstance().postAsync(pubClass.Server_namehzm, new OkHttpManger.MyCallback() {
                @Override
                public void onSuccess(String result) {
                    String[] array=result.split("\\|");
                    if(array[0].equals("200")){
                        //
                        Gson gson=new Gson();
                        Type typeList=new TypeToken<ArrayList<Employee>>(){}.getType();
                        emp=gson.fromJson(pubClass.convertToArrayJson(result),typeList);

                        //判断是否有数据，控制推送人显示或隐藏
                        if(emp.size()!=0){
                            hindTuisong.setVisibility(View.VISIBLE);
                        }else{
                            hindTuisong.setVisibility(View.GONE);
                        }
                    }
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }

                @Override
                public void onFailture() {
                    if (pdialog.isShowing()){
                        pdialog.dismiss();
                    }
                }
            },map);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void getTempLostRRPoint() throws DbException {
        List<tempLostRR> lostRR = db.selector(tempLostRR.class).where("schId","=",schId).findAll();
        for (tempLostRR rr:lostRR){

        }
    }


    public void upLoadCheck(int schId){
        List<tempLostRR> temp=null;
        try {
            //拿到上传的数据
            temp = db.selector(tempLostRR.class).where("schId", "=", schId).findAll();
        }catch (DbException e) {
            e.printStackTrace();
        }
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime=sdf.format(date);
            try {
              thisSch = db.selector(Schedule.class).where("ID","=", schId).findFirst();
                if (thisSch!=null){
                    upLoadDsOrScore(schId,currentTime,temp);
                }
            } catch (DbException e) {
                e.printStackTrace();
            }

    }

    /**
     * 上传的评论和分数
     * @param schId
     * @param startTime
     * @param list
     */
    public void  upLoadDsOrScore( final int schId, final String startTime, List<tempLostRR> list){
        status.setText("正在进行数据提交......");
        JSONObject obj=new JSONObject();
        Map<String,Object> map=new HashMap<>();
        Gson gson=new Gson();
        map.put("task","getReportItemFromDevice");
        map.put("schid",schId);
        map.put("schstarttime",startTime);
        map.put("tIrrList", gson.toJson(list));

        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                String[] resArry= result.split("\\|");
                if(resArry[0].equals("200")){
                    Toast.makeText(SubmitReport.this,"数据上传成功",Toast.LENGTH_SHORT).show();
                    if(thisSch.getStates()==1||thisSch.getRealStartTime()==null)
                    {
                       /*应于数据提交成功后修改状态*/
                        try {
                            thisSch.setStates(3);
                            thisSch.setRealStartTime(startTime);
                            db.saveOrUpdate(thisSch);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                    CommonMapBean cmb=new CommonMapBean();
                    cmb.setCmType("fenshu");
                    cmb.setServerId(schId);
                    cmb.setCmValue(resArry[3]);
                    try {
                        db.saveOrUpdate(cmb);
                       Schedule schedule=db.selector(Schedule.class).where("ID","=",schId+"").findFirst();

                    }catch (DbException e)
                    {
                        e.printStackTrace();
                    }
                    upLoadImage(schId);

                }else if(resArry[0].equals("201")) {
                    Toast.makeText(SubmitReport.this,"数据上传失败",Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(SubmitReport.this,resArry[1].toString(),Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                BaseActivity.showAnimaDialog(SubmitReport.this,"网络连接错误");
                status.setText("上传失败，请检查网络状态");
                completeUpload(failed);
            }
        });
    }

    /**
     * 上传的图片和视频
     * @param schId
     */
    public  void upLoadImage(final int schId){

        int count=0;
        try {
            List<tempLostRR> rrlist = null;
            rrlist = db.selector(tempLostRR.class).where("schId", "=",schId).findAll();
            Map<String, Object> map = new HashMap<>();
            map.put("task", "getReportJpgFromDevice");
            if (rrlist!=null&&rrlist.size()>0){
                status.setText("正在上传图片和视频");
                for (tempLostRR rr : rrlist) {
                    String[] ss = rr.getJpgStr().split(",");
                    String[] sp=rr.getVideoStr().split(",");
                    for (String s : ss) {
                        //裁剪时已经进行压缩
                        File f = new File(s);
                        map.put("uploadfile"+count, f);
                        count++;
                    }
                    for (String p:sp){
                        File f = new File(p);
                        map.put("uploadfile"+count, f);
                        count++;
                    }
                }
                pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Toast.makeText(SubmitReport.this,"图片视频上传成功",Toast.LENGTH_SHORT).show();
                        uploadsignCon(schId);
                        asynScheduleData(MainActivity.id);
                    }
                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        Toast.makeText(SubmitReport.this,"图片视频上传失败",Toast.LENGTH_SHORT).show();;
                        uploadsignCon(schId);
                    }
                });
            }
            else{
                //没照片就不上传，进行签名上传
                uploadsignCon(schId);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }
    /**
     * 此处上传用户的签字数据，不管是否有数据，最后都会执行上传签名，除了网络问题
     * @param schId
     */
    public  void uploadsignCon(int schId){

        try {
            CommonMapBean cmb = new CommonMapBean();
            cmb = db.selector(CommonMapBean.class).where("CmType", "=", "门店签名")
                    .and("IndexNum", "=", schId + "")
                    .findFirst();
            if(cmb!=null) {
                status.setText("正在上传门店签名...");
                Map<String, Object> map = new HashMap<>();
                map.put("task", "getsignconFromDevice");
                map.put("schid", schId + "");
                File f = new File(cmb.getCmValue().toString());
                map.put("uploadfile", f);

                pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);
                        Toast.makeText(SubmitReport.this,"签名上传成功",Toast.LENGTH_SHORT).show();
                        status.setText("签名上传成功！");
                        completeUpload(success);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        Toast.makeText(SubmitReport.this,"签名上传失败",Toast.LENGTH_SHORT).show();
                        status.setText("签名上传失败！");
                        completeUpload(success);

                    }
                });
            }else {
                status.setText("上传完毕");
                completeUpload(success);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void completeUpload(String text){
            titleText.setText(text);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(dialog!=null)
                        dialog.dismiss();
                    //SubmitReport.this.finish();
                    setResult(100);
                    finish();

                }
            }, 2000);
    }




    /**
     * 刷新数据
     * @param employeeid
     * @return
     */
    public  int asynScheduleData(int employeeid) {
        Map<String,Object> map=new HashMap<>();
        map.put("task","loadScheduleByEmpId");
        map.put("empid",String.valueOf(employeeid));
        pubClass.Post(pubClass.Server_namehzm,map,new pubClass.MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                asynScheduleData(result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
        return 0;
    }

    /**
     * 数据的判断与本地的更新
     * @param result
     */
    private  void asynScheduleData(String result) {
        String[] resArry = result.split("\\|");
        if (resArry[0].equals("200")) {
            Gson gson = new Gson();
            //UserInfo user=gson.fromJson(strings[0],UserInfo.class);
            Type typeList = new TypeToken<ArrayList<Schedule>>() {
            }.getType();
            ArrayList<Schedule> Schedules = gson.fromJson(pubClass.convertToArrayJson(result), typeList);
            for (Schedule ee : Schedules
                    ) {
                try {
                    Schedule dbSch = db.selector(Schedule.class).where("ID", "=", String.valueOf(ee.getID())).findFirst();
                    if (dbSch != null)//如果服务器端的任务已经是先于本地端 则更新本地数据。
                    {
                        if (ee.getStates() > dbSch.getStates()) {
                            ee.set_ID(dbSch.get_ID());
                            db.saveOrUpdate(ee);
                        }
                    } else
                        db.saveOrUpdate(ee);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if(dialog!=null) {
                dialog.dismiss();
            }
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.silde_bottom_out);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {

        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.silde_bottom_out);
    }

    @Override
    public void finish() {
        if(dialog!=null)
            dialog.dismiss();
        super.finish();
        overridePendingTransition(R.anim.slide_bottom_in, R.anim.silde_bottom_out);
    }

    @Override
    protected void onDestroy() {
        if(dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
    }

}
